package com.jeff.practice;

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ArrayBlockingQueue;

public class CustomThreadPoolExample {
    public static void main(String[] args) {
        // 设置线程池参数
        int corePoolSize = 30; // 核心线程数
        int maximumPoolSize = 30; // 最大线程数
        long keepAliveTime = 60; // 线程存活时间
        TimeUnit unit = TimeUnit.SECONDS; // 时间单位
        int queueCapacity = 20; // 队列容量

        // 创建任务队列
        ArrayBlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(queueCapacity);

        // 创建线程池
        try (ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit,
                workQueue, new ThreadPoolExecutor.AbortPolicy() // 拒绝策略
        )) {

            // 提交任务
            for (int i = 0; i < 30; i++) {
                final int taskId = i;
                executor.submit(() -> {
                    System.out.println("Executing task " + taskId + " in thread " + Thread.currentThread().getName()+
                            "-"+ Calendar.getInstance().getTime().getSeconds());
                    try {
                        // 模拟任务执行
                        Thread.sleep(1000);
                    }
                    catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                });
            }

            // 关闭线程池
            executor.shutdown();
            try {
                // 等待线程池中的任务完成
                if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                    executor.shutdownNow(); // 强制关闭
                }
            }
            catch (InterruptedException e) {
                executor.shutdownNow();
            }
        }

        System.out.println("All tasks completed.");
    }
}
